/*
 * @Author: 郝奔 1425466221@qq.com
 * @Date: 2024-12-05 16:01:34
 * @LastEditors: 郝奔 1425466221@qq.com
 * @LastEditTime: 2024-12-26 10:33:30
 * @FilePath: /HG-dqbasic_open_platform/src/directive/permission/index.ts
 * @Description: 
 * Copyright (c) 2024-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
 */
import { useUserStoreHook } from '@/framework/store/modules/user';
import { Directive, DirectiveBinding } from 'vue';
import { usePermissionStoreHook } from '@/framework/store/modules/permission';

/**
 * 按钮权限校验
 */
export const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    // 「超级管理员」拥有所有的按钮权限
    const { roles, perms } = useUserStoreHook();
    const { buttonCodes } = usePermissionStoreHook()
    if (roles.includes('ROOT')) {
      return true;
    }
    // 「其他角色」按钮权限校验
    const { value } = binding;
    if (value) {
      const requiredPerms = value; // DOM绑定需要的按钮权限标识

      // const hasPerm = perms?.some(perm => {
      //   return requiredPerms.includes(perm);
      // });
      const hasPerm = buttonCodes?.some((buttonCode: string) => {
        return requiredPerms.includes(buttonCode);
      });

      if (!hasPerm) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error(
        "need perms! Like v-has-perm=\"['sys:user:add','sys:user:edit']\""
      );
    }
  }
};

/**
 * 角色权限校验
 */
export const hasRole: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;

    if (value) {
      const requiredRoles = value; // DOM绑定需要的角色编码
      const { roles } = useUserStoreHook();
      const hasRole = roles.some(perm => {
        return requiredRoles.includes(perm);
      });

      if (!hasRole) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error("need roles! Like v-has-role=\"['admin','test']\"");
    }
  }
};
